package com.jw.blog.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jw.blog.utils.UserIpUtil;
import com.jw.blog.wblog.entity.BlackIp;
import com.jw.blog.wblog.mapper.BlackIpMapper;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author wan Email-wlf18726994755@163.com
 * @version 1.0
 * @className IpFilter
 * @date 2020/7/1 12:50
 **/
@WebFilter
public class IpFilter implements Filter {

    @Resource
    private BlackIpMapper blackIpMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        // 获取到用户的IP
        String ip = UserIpUtil.getIp(httpServletRequest);

        BlackIp blackIp = null;
        QueryWrapper<BlackIp> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(BlackIp::getIp,ip);
        List<BlackIp> blackIps = blackIpMapper.selectList(wrapper);
        if (blackIps.size() == 0) {
            chain.doFilter(httpServletRequest, httpServletResponse);
            return;
        } else {
            httpServletRequest.getRequestDispatcher("/blackIp").forward(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
